package com.jdy.haoduoai.adapter;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.activity.AddHabitClockActivity;
import com.jdy.haoduoai.activity.BaseActivity;
import com.jdy.haoduoai.activity.PainPointDiscussionActivity;
import com.jdy.haoduoai.fragment.TabIndexFragment;
import com.jdy.haoduoai.model.HabitMedia;
import com.jdy.haoduoai.model.HabitPlan;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.PainPointItem;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.widget.CustomTimeDialog;
import com.jdy.haoduoai.widget.CustomTimeDialog.Builder.OnOkClickListener;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;

//import com.jdy.haoduoai.R;

//import com.jdy.haoduoai.util.ImHelper;


/**
 * 习惯养成
 * 
 * @author hf
 * 
 */
@SuppressLint("InflateParams")
public class HabitPlanAdapter extends BaseAdapter {
  private BaseActivity mContext;
  private ArrayList<HabitPlan> mList;
  private LayoutInflater mInflater;
  private HabitMedia mHabitMusic;
  private OnSetAlarmListener mOnSetAlarmListener;
  private CustomTimeDialog timeDlg;

  public OnSetAlarmListener getOnSetAlarmListener() {
    return mOnSetAlarmListener;
  }

  public void updatePlayingInfo(HabitMedia hm) {
    mHabitMusic = hm;
    notifyDataSetChanged();
  }

  // public void updatedata(ArrayList<HabitPlan> list) {
  // mList = list;
  // }

  public void setOnSetAlarmListener(OnSetAlarmListener mmOnSetAlarmListener) {
    this.mOnSetAlarmListener = mmOnSetAlarmListener;
  }

  public interface OnSetAlarmListener {
    void finishSetAlarm();
  }

  public void setData(ArrayList<HabitPlan> list) {
    mList = list;
  }

  public void updateListData (ArrayList<HabitPlan> list) {
      this.mList = list;
  }

  public HabitPlanAdapter(BaseActivity context, ArrayList<HabitPlan> list,
                          ListView lll) {
    this.mContext = context;
    this.mList = list;
    mInflater = LayoutInflater.from(mContext);
  }

  @Override
  public int getCount() {
    return mList.size();
  }

  @Override
  public Object getItem(int position) {
    return mList.get(position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  private void setHabitTime(final HabitPlan iitem) {
    CustomTimeDialog.Builder customBuilder = new CustomTimeDialog.Builder(
        mContext);
    customBuilder.setTitle("设置每次启动时间")
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
        }).setPositiveButton("确定", new OnOkClickListener() {
          @Override
          public void onClickOk(final int hourOfDay, final int minute) {
            timeDlg.dismiss();

            Async.start(new Func0<ResponseResult>() {
              @Override
              public ResponseResult call() {
                LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                if (lu == null) {
                  lu = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                param_.put("time", String.format("%02d", hourOfDay) + ":"
                    + String.format("%02d", minute));

                if (iitem.is_customized == 1) {
                  return HttpUtils.startRequest(HttpUtils.API_URL
                                  + "/api/2.0/operation/habit/habits_customized/" + iitem.habit_id, param_,
                          HttpUtils.TAG_PUT_REQUEST);
                } else {
                  return HttpUtils.startRequest(HttpUtils.API_URL
                                  + "/api/2.0/operation/habit/habits_plan/" + iitem.id, param_,
                          HttpUtils.TAG_PUT_REQUEST);
                }


              }
            }).filter(new Func1<ResponseResult, Boolean>() {
              @Override
              public Boolean call(ResponseResult arg0) {
                return arg0 != null && Tools.isNotEmpty(arg0)
                    && arg0.isSuccess();
              }
            }).doOnCompleted(new Action0() {
              @Override
              public void call() {
                // TODO
              }
            }).subscribe(new Action1<ResponseResult>() {
              @Override
              public void call(ResponseResult result) {
                if (mOnSetAlarmListener != null && result.isSuccess()) {
                  mOnSetAlarmListener.finishSetAlarm();
                }
              }
            });

          }
        });

    if (!mContext.isFinishing()) {
      timeDlg = customBuilder.create();
      timeDlg.show();
    }
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    final HabitPlan item = mList.get(position);
    final ViewHolder holder;
    if (convertView == null) {
      convertView = mInflater.inflate(R.layout.story_item, null);
      holder = new ViewHolder();
      holder.pb_day = (ProgressBar) convertView.findViewById(R.id.pb_day);
      holder.tv_label = (TextView) convertView.findViewById(R.id.tv_label);
      holder.tv_insistdays = (TextView) convertView
          .findViewById(R.id.tv_insistdays);
      holder.tv_morningsong = (TextView) convertView
          .findViewById(R.id.tv_morningsong);
      holder.tv_clock = (TextView) convertView.findViewById(R.id.tv_clock);
      holder.bg = (Button) convertView.findViewById(R.id.bg);
      holder.img_palyorpause = (ImageView) convertView
          .findViewById(R.id.img_palyorpause);
      holder.jiaobiao_img = (ImageView) convertView
              .findViewById(R.id.jiaobiao_img);
      holder.slayout = convertView.findViewById(R.id.slayout);
      holder.img_palyorpause.setTag(false);
      holder.img = (ImageView) convertView.findViewById(R.id.img);
      convertView.setTag(holder);
    } else {
      holder = (ViewHolder) convertView.getTag();
    }

    holder.pb_day.setMax(10 * 21);

    Drawable drawable2 = mContext.getResources().getDrawable(R.drawable.clock);

    if (item != null) {
      holder.tv_morningsong.setText(item.name);
      int lastIdx = item.time.lastIndexOf(":");
      holder.tv_clock.setText(item.time.substring(0, lastIdx));

      Drawable drawable = mContext.getResources().getDrawable(
          R.drawable.edit_habit);

      if (TabIndexFragment.allowEditTime >= 0) {
        drawable = mContext.getResources().getDrawable(R.drawable.edit_habit);
      } else if (TabIndexFragment.allowEditTime < 0) {
        drawable = mContext.getResources().getDrawable(
            R.drawable.edit_habit_disable);
      }

      drawable.setBounds(0, 0, drawable.getMinimumWidth(),
          drawable.getMinimumHeight());
      drawable2.setBounds(0, 0, drawable2.getMinimumWidth(),
          drawable2.getMinimumHeight());
      holder.tv_clock.setTag(false);

      if (item.is_customized == 2) {
        holder.tv_clock.setCompoundDrawables(drawable2, null, null, null);
      } else {
        holder.tv_clock.setCompoundDrawables(drawable2, null, drawable, null);
      }

      holder.tv_clock.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
          if (item.is_customized == 2) {
            return;
          }

          boolean clockTag = (boolean) holder.tv_clock.getTag();
          if (TabIndexFragment.allowEditTime >= 0 && !clockTag) {
            if (item.is_customized == 1) {
              setHabitTime(item);
            } else {
              setHabitTime(item);
            }
          }
        }
      });

      if (item.is_customized == 2) {
        holder.jiaobiao_img.setVisibility(View.VISIBLE);
      } else {
        holder.jiaobiao_img.setVisibility(View.GONE);
      }

      holder.img_palyorpause.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
      holder.tv_insistdays.setText(Html.fromHtml("已坚持<font color= '#42b2f7'>"+ item.day + "</font>" + "天"));
      holder.pb_day.setProgress(10 * item.day);

      if (Tools.isNotEmpty(item.img)) {
        if (Tools.isEmpty(holder.img.getTag())) {
          Picasso.with(mContext).load(item.img).into(holder.img);
          holder.img.setTag(item.img);
        } else {
          if (item.img.equals(holder.img.getTag())) {
            // TODO
          } else {
            Picasso.with(mContext).load(item.img).into(holder.img);
            holder.img.setTag(item.img);
          }
        }
      }

      if (item.status == 1) {
        holder.bg.setText("已执行");
        holder.bg.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
      } else {

        if (mHabitMusic != null && mHabitMusic.id == item.id && Tools.isNotEmpty(mHabitMusic.is_customized)
                && mHabitMusic.is_customized.contains("" + item.is_customized)) {
          // TODO
        } else {
          holder.bg.setText("未执行");
          holder.bg.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
        }
      }

      holder.slayout.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

          if (item.is_customized == 2) {
            return;
          }

          if (item.is_customized == 1) {
            Intent intent = new Intent();
            intent.setClass(mContext, AddHabitClockActivity.class);
            intent.putExtra("isedit", true);

            PainPointItem item2 = new PainPointItem();
            item2.id = item.habit_id;
            item2.img = item.img;
            item2.name = item.name;
            item2.time = item.time;
            item2.enable = 1;
            item2.macid = item.macid;
            item2.mp3_url = item.mp3_url;

            intent.putExtra("custompainpoint", item2);
            mContext.startActivity(intent);
          } else {
            if (TabIndexFragment.mPainPointList != null
                    && !TabIndexFragment.mPainPointList.isEmpty()) {
              for (PainPointItem ppi : TabIndexFragment.mPainPointList) {
                if (item.habit_id == ppi.id) {
                  Intent t = new Intent(mContext,
                          PainPointDiscussionActivity.class);
                  t.putExtra("name", ppi.name);
                  t.putExtra("number", ppi.user_number);
                  t.putExtra("img", ppi.img);
                  t.putExtra("desc", ppi.desc);
                  t.putExtra("desc_short", ppi.desc_short);
                  t.putExtra("habit_id", ppi.id);
                  t.putExtra("selected", ppi.selected);
                  Bundle extraBundle = new Bundle();
                  extraBundle.putIntegerArrayList("selected_list",
                          TabIndexFragment.mSelectedPainPointIds);
                  t.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                  t.putExtras(extraBundle);
                  mContext.startActivity(t);
                  break;
                }
              }
            }
          }
        }
      });
    }

    holder.img_palyorpause.setClickable(true);

    if (mHabitMusic != null && mHabitMusic.id == item.id && Tools.isNotEmpty(mHabitMusic.is_customized)
            && mHabitMusic.is_customized.contains("" + item.is_customized)) {
      holder.img_palyorpause.setVisibility(View.VISIBLE);
      if (item.status == 1) {
        holder.bg.setText("已执行");
        holder.bg.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
        holder.img_palyorpause.setClickable(false);
        holder.img_palyorpause.setBackgroundResource(R.drawable.play_gray);

        if (Tools.isNotEmpty(mHabitMusic.PlayState)
            && (mHabitMusic.PlayState.contains("stop") )) {
          holder.bg.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
          holder.bg.setText("已执行");
          holder.bg.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
          holder.img_palyorpause.setClickable(false);
          holder.img_palyorpause.setBackgroundResource(R.drawable.play_gray);

          Drawable drawable = mContext.getResources().getDrawable(
              R.drawable.edit_habit);
          drawable.setBounds(0, 0, drawable.getMinimumWidth(),
              drawable.getMinimumHeight());
          holder.tv_clock.setCompoundDrawables(drawable2, null, drawable, null);
          holder.tv_clock.setTag(false);
        } else {
//          holder.bg.setText("播放中");
//          holder.img_palyorpause.setClickable(true);
        }

        if (Tools.isNotEmpty(mHabitMusic.PlayState)) {
          if (Tools.isNotEmpty(mHabitMusic.PlayState)
              && mHabitMusic.PlayState.contains("playing")) {
            holder.img_palyorpause.setBackgroundResource(R.drawable.pause_blue);
          } else {
            holder.img_palyorpause.setBackgroundResource(R.drawable.play_blue);
          }

          Drawable drawable = mContext.getResources().getDrawable(
              R.drawable.edit_habit_disable);
          drawable.setBounds(0, 0, drawable.getMinimumWidth(),
              drawable.getMinimumHeight());
          holder.tv_clock.setCompoundDrawables(drawable2, null, drawable, null);
          holder.tv_clock.setTag(true);
        }

        if (Tools.isNotEmpty(mHabitMusic.PlayState)
            && (mHabitMusic.PlayState.contains("stop"))) {
          holder.bg.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
          holder.bg.setText("已执行");
          holder.bg.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
          holder.img_palyorpause.setClickable(false);
          holder.img_palyorpause.setBackgroundResource(R.drawable.play_gray);

          Drawable drawable = mContext.getResources().getDrawable(
              R.drawable.edit_habit);
          drawable.setBounds(0, 0, drawable.getMinimumWidth(),
              drawable.getMinimumHeight());
          holder.tv_clock.setCompoundDrawables(drawable2, null, drawable, null);
          holder.tv_clock.setTag(false);
        }

        holder.img_palyorpause.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {
              if (Tools.isNotEmpty(mHabitMusic.PlayState)
                  && mHabitMusic.PlayState.contains("playing")) {
                JSONObject jsonObject = new JSONObject();
                try {
                  jsonObject.put("code", 202);
                  jsonObject.put("act", "ctlvideo");
                  jsonObject.put("data", "pause");
                  SocketThreadManager.getInstance().send(jsonObject.toString());
                } catch (JSONException e) {
                  e.printStackTrace();
                }
              } else {
                JSONObject jsonObject = new JSONObject();
                try {
                  jsonObject.put("code", 202);
                  jsonObject.put("act", "ctlvideo");
                  jsonObject.put("data", "resume");
                  SocketThreadManager.getInstance().send(jsonObject.toString());
                } catch (JSONException e) {
                  e.printStackTrace();
                }
              }
          }
        });
      } else {
        holder.img_palyorpause.setClickable(true);
        holder.bg.setText("播放中");
        if (Tools.isNotEmpty(mHabitMusic.PlayState)
            && (mHabitMusic.PlayState.contains("stop") )) {
          holder.bg.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
          holder.bg.setText("已执行");
        } else {
         // holder.bg.setTextSize(TypedValue.COMPLEX_UNIT_SP, 7);
        }

        if (Tools.isNotEmpty(mHabitMusic.PlayState)) {
          if (Tools.isNotEmpty(mHabitMusic.PlayState)
              && mHabitMusic.PlayState.contains("playing")) {
            // 播放中
            holder.img_palyorpause.setBackgroundResource(R.drawable.pause_blue);
          } else {
            // 暂停
            holder.img_palyorpause.setBackgroundResource(R.drawable.play_blue);
          }

          Drawable drawable = mContext.getResources().getDrawable(
              R.drawable.edit_habit_disable);
          drawable.setBounds(0, 0, drawable.getMinimumWidth(),
              drawable.getMinimumHeight());
          holder.tv_clock.setCompoundDrawables(drawable2, null, drawable, null);
          holder.tv_clock.setTag(true);
        }

        if (Tools.isNotEmpty(mHabitMusic.PlayState)
            && (mHabitMusic.PlayState.contains("stop"))) {
          holder.bg.setText("已执行");
          holder.bg.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
          holder.img_palyorpause.setClickable(false);
          holder.img_palyorpause.setBackgroundResource(R.drawable.play_gray);

          Drawable drawable = mContext.getResources().getDrawable(
              R.drawable.edit_habit);
          drawable.setBounds(0, 0, drawable.getMinimumWidth(),
              drawable.getMinimumHeight());
          holder.tv_clock.setCompoundDrawables(drawable2, null, drawable, null);
          holder.tv_clock.setTag(false);
        }

        holder.img_palyorpause.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {
              if (Tools.isNotEmpty(mHabitMusic.PlayState)
                  && mHabitMusic.PlayState.contains("playing")) {
                JSONObject jsonObject = new JSONObject();
                try {
                  jsonObject.put("code", 202);
                  jsonObject.put("act", "ctlvideo");
                  jsonObject.put("data", "pause");
                  SocketThreadManager.getInstance().send(jsonObject.toString());
                } catch (JSONException e) {
                  e.printStackTrace();
                }
              } else {
                JSONObject jsonObject = new JSONObject();
                try {
                  jsonObject.put("code", 202);
                  jsonObject.put("act", "ctlvideo");
                  jsonObject.put("data", "resume");
                  SocketThreadManager.getInstance().send(jsonObject.toString());
                } catch (JSONException e) {
                  e.printStackTrace();
                }
              }
          }
        });
      }
    } else {
      holder.img_palyorpause.setClickable(false);
      holder.img_palyorpause.setBackgroundResource(R.drawable.play_gray);
    }

    return convertView;
  }

  private static class ViewHolder {
    ProgressBar pb_day;
    TextView tv_label;// 21tian
    TextView tv_insistdays; // 已堅持
    TextView tv_morningsong; // 清晨刷牙歌
    TextView tv_clock;
    Button bg; // "已完成"
    View slayout, jiaobiao_img;
    ImageView img, img_palyorpause;
  }

}
